<template>
  <el-container>
    <el-aside width="250px">
      <DatabaseInfo @open="handleOpen" @close="handleClose" @select="handleSelect" :db-info="props.dbInfo"
        :database-info="props.databaseInfo"></DatabaseInfo>
    </el-aside>
    <el-main style="padding:12px;">
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane :label="`已选择数据库：${currentDb}`" name="tableInfo">
          <!--超表列表详情-->
          <el-form :inline="true">
            <el-form-item label="">
              <el-input size="small" placeholder="请输入主题名" v-model="searchWord" clearable />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchConidtionST()" class="el-icon-search" :icon="Search"
                size="small">查询</el-button>
              <el-button type="default" @click="syncDataSub" class="el-icon-plus" size="small"
                :icon="Share">订阅同步数据</el-button>
            </el-form-item>
          </el-form>
          <!-- <el-table-v2 :columns="stableColumns" :data="stData" :width="dialogWidth" :height="height" fixed /> -->
          <el-table style="height: calc(100% - 82px);" v-loading="loading" border :data="stData" :width="dialogWidth"
            @selection-change="handleSelectionChange">
            <template #empty>
              <el-empty />
            </template>
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column prop="topicName" label="主题名" width="200">
            </el-table-column>
            <el-table-column prop="dbName" label="数据库" width="200" show-overflow-tooltip>

            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="200" show-overflow-tooltip>

            </el-table-column>
            <el-table-column prop="sql" label="SQL" width="300" show-overflow-tooltip>

            </el-table-column>
            <el-table-column fixed="right" label="操作" minWidth="300">
              <template v-slot="scope">
                <el-button type="primary" plain @click="btn_editTables(scope.row)">编辑</el-button>
                <el-button type="danger" :disabled="scope.row.tagStatue == '已同步'" plain
                  @click="btn_deleteTables(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div style="margin-top: 8px;">
            <el-button style="float:left;" type="default" plain @click="btn_batchDeleteTables()">批量删除</el-button>
            <el-pagination style="float:right;" v-model:current-page="currentPage" v-model:page-size="pageSize"
              :page-sizes="[10, 100, 200, 400]" :size="size" :disabled="disabled" :background="background"
              layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
              @current-change="handleCurrentChange" />
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-main>
    <el-dialog v-model="dialogVisible" title="数据库配置信息" width="80%" draggable :close-on-click-modal="false"
      :before-close="closeDialog">
      <el-form :inline="true" :model="databaseModel" label-width="150px">
        <el-row>
          <el-col :span="spanLength">
            <el-form-item label="数据库名称">
              <el-input v-model="databaseModel.name" placeholder="数据库名称" class="formItemDialog"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="spanLength">
            <el-form-item label="数据库ip">
              <el-input v-model="databaseModel.host" placeholder="数据库ip" class="formItemDialog"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="spanLength">
            <el-form-item label="数据库端口号">
              <el-input v-model="databaseModel.port" placeholder="数据库端口号" class="formItemDialog"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="spanLength">
            <el-form-item label="数据库用户名">
              <el-input v-model="databaseModel.username" placeholder="数据库用户名" class="formItemDialog"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="spanLength">
            <el-form-item label="数据库密码">
              <el-input v-model="databaseModel.password" placeholder="数据库密码" class="formItemDialog"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="spanLength">
            <el-form-item label="订阅成功数量">
              <el-input v-model="databaseModel.successCount" placeholder="订阅成功数量" class="formItemDialog"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
          </el-col>
          <el-col :span="12">
            <el-button style="float: right;margin-left: 10px;" @click="closeDialog">关闭</el-button>
            <el-button style="float: right;" type="primary" @click="startSync">开始同步</el-button>
          </el-col>

        </el-row>
      </el-form>
    </el-dialog>
  </el-container>


</template>

<script lang="tsx" setup>

import { ref, toRaw, watch, defineProps } from 'vue'
import { onMounted, onBeforeUnmount } from 'vue'
import { ArrowDown } from '@element-plus/icons-vue'
import { Delete, Edit, Search, Share, Upload, Download, Link } from '@element-plus/icons-vue'
import { ElMessage, ElButton, TableV2FixedDir, ElTooltip, ElIcon, ElTag, ComponentSize, ElMessageBox } from 'element-plus'
import { showTopics, deleteTopics, syncDataSubInfo, closeSyncDataSubInfo, getResCount } from '@/api/dataSubscription'
import { defaultAxios } from '@/utils/http/index.js'

//属性值
const props = defineProps({
  dbInfo: {
    type: Object,
    default: {},
  },
  databaseInfo: {
    type: Array,
    default: [],
  }
})

// import TableDialog from "./TableDialog.vue"

//table还是stable
const tableType = ref('table');
const dialogVisible = ref(false);

const uploadDialogVisible = ref(false);
import { genFileId } from 'element-plus'
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
import axios from 'axios'
import DatabaseInfo from '../../components/DatabaseInfo.vue'
const upload = ref<UploadInstance>()
const actionUrl = ref('');
const updateTagDescUrl = ref("")
const updateTagTnUrl = ref("")


const databaseModel = ref({ name: "", isDelete: false, host: "", port: "", username: "", password: "", vgroups: 4, buffer: 256, cachesize: 1, cachemodel: "last_row", successCount: 0 });


const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const size = ref<ComponentSize>('default')
const background = ref(false)
const disabled = ref(false)
const multipleSelection = ref([])

//导入子表1 2删除子表  3修改测点描述信息   4修改tn信息
const dialogType = ref(1)

const loading = ref(false)
const height = ref();
const tableWidth = ref(0);
const dialogWidth = ref(0);
const spanLength = ref(6);


const store = {
  info: props.dbInfo,
  databaseInfo: props.databaseInfo
};
const currentDb = ref('');
const currentStable = ref('');

//数据
const data = ref([]);
const columns = ref([]);

const subTableData = ref([]);


//超表搜索条件
const searchWord = ref('');
//超表数据
const stData = ref([]);
//超表结构数据
const stableColumns = ref([
  {
    key: 'tagName',
    title: '表名',
    dataKey: 'tagName',
    width: 300,
    align: 'center',
    cellRenderer: ({ cellData: tagName }) => <ElTag>{tagName} </ElTag>,
  },
  {
    key: 'tagDesc',
    title: '描述',
    dataKey: 'tagDesc',
    width: 300,
    align: 'center',
    cellRenderer: ({ cellData: tagDesc }) => <ElTag>{tagDesc} </ElTag>,
  },
  {
    key: 'tagType',
    title: '类型',
    dataKey: 'tagType',
    width: 300,
    align: 'center',
    cellRenderer: ({ cellData: tagType }) => <ElTag>{tagType} </ElTag>,
  },
]);
//在操作列添加按钮操作
// <ElButton size="small" > 编辑 </ElButton>
// <ElButton size="small" type="danger" >删除</ElButton>

//表数据
const tData = ref([]);

//tab页
const activeName = ref('tableInfo');

const handleOpen = (key: string, keyPath: string[]) => {
  console.log(key, keyPath)
  currentDb.value = key;
}


/**
 * 订阅同步数据
 */
const syncDataSub = (key: string, keyPath: string[]) => {
  if (currentDb.value == null || currentDb.value == '') {
    ElMessage({
      message: '请先选择数据库再进行初始化超表',
      type: 'error',
    });
    return;
  }
  if (multipleSelection.value.length != 1) {
    ElMessage({
      message: '请选择一个主题进行订阅同步测试',
      type: 'error',
    });
    return;
  }

  databaseModel.value.host = store.info.host;
  databaseModel.value.port = store.info.port;
  databaseModel.value.username = store.info.username;
  databaseModel.value.password = store.info.password;
  dialogVisible.value = true;
}



/**
 * 获取订阅数量
 */
const getSyncDataSubCount = () => {
  console.log("获取订阅数量:" + "getSyncDataSubCount")
  getResCount().then(r => {
    databaseModel.value.successCount = r.data;
    loading.value = false;
    //每隔5秒查询一次
    setTimeout(() => {
      console.log("定时获取订阅数量:" + "getResCount")
      getSyncDataSubCount();
    }, 5000);

  }).catch(err => {
    console.log(err)
    //每隔5秒查询一次
    setTimeout(() => {
      getResCount();
    }, 5000);
    ElMessage({
      message: '查询数据失败',
      type: 'error',
    });
    loading.value = false;
  });
}

const startSync = () => {
  //初始化超级表需要的参数
  let payload = {
    ...store.info,
    dbName: currentDb.value
  };

  let param = {
    dbConfig: payload,
    tDengineConfigDto: databaseModel.value,
    dataList: multipleSelection.value,
  }
  // dialogVisible.value = false;
  syncDataSubInfo(param).then(r => {
    ElMessage({
      message: '开始同步',
      type: 'success',
    });

    getSyncDataSubCount();
  }).catch(err => {
    ElMessage({
      message: '同步失败',
      type: 'error',
    });
  });
}

const closeDialog = () => {
  console.log("关闭dialog")
  dialogVisible.value = false;
  //关闭dialog
  let payload = {
    ...store.info,
    dbName: currentDb.value
  };

  let param = {
    dbConfig: payload,
    tDengineConfigDto: databaseModel.value,
    dataList: multipleSelection.value,
  }

  closeSyncDataSubInfo(param).then(r => {
    ElMessage({
      message: '关闭同步',
      type: 'success',
    });

  }).catch(err => {
    ElMessage({
      message: '关闭同步失败',
      type: 'error',
    });
  });
}


//选择数据库
const handleSelect = (key: string, keyPath: string[]) => {
  currentDb.value = key;
  searchWord.value = "";
  /**
   * 获取table列表
   */
  let payload = {
    ...store.info,
    dbName: currentDb.value
  };
  let param = {
    dbConfig: payload,
    tableName: searchWord.value,
    pageSize: pageSize.value,
    currentPage: currentPage.value
  }
  loading.value = true;
  showTopics(param).then(r => {
    stData.value = r.data.records.map((item: any, index: number) => {
      return item;
    });
    total.value = r.data.total;
    loading.value = false;
  }).catch(err => {
    ElMessage({
      message: '查询数据失败',
      type: 'error',
    });
    loading.value = false;
  });
}

const handleClose = (key: string, keyPath: string[]) => {
  console.log(key, keyPath)
}


const handleSelectionChange = (val) => {
  multipleSelection.value = val
}
/**
 * 编辑操作
 */
const btn_editTables = (cellData) => {
  ElMessage({
    message: '待开发',
    type: 'error',
  });
}
/**
 * 删除操作
 */
const btn_deleteTables = (cellData) => {
  ElMessageBox.confirm('请确认是否删除该表记录?')
    .then(() => {
      let params = [];
      params.push(cellData);
      let payload = {
        ...store.info,
        dbName: currentDb.value
      };
      let param = {
        dbConfig: payload,
        dataList: params,
      }
      deleteTopics(param).then(r => {
        searchConidtionST();
      })
    })
    .catch(() => {
      ElMessage({
        message: '已取消',
        type: 'success',
      });
    })
}
/**
 * 批量删除操作
 */
const btn_batchDeleteTables = (cellData) => {
  ElMessageBox.confirm('请确认是否删除该表记录?')
    .then(() => {
      let payload = {
        ...store.info,
        dbName: currentDb.value
      };
      let param = {
        dbConfig: payload,
        dataList: multipleSelection.value,
      }

      deleteTopics(param).then(r => {
        searchConidtionST();
      })
    })
    .catch(() => {
      ElMessage({
        message: '已取消',
        type: 'success',
      });
    })
}

onMounted(() => {
  actionUrl.value = defaultAxios.getBaseUrl() + "/api/tdengine/managerpoints/uploadFile";
  updateTagDescUrl.value = defaultAxios.getBaseUrl() + "/api/tdengine/managerpoints/updateTagDescByFile";
  updateTagTnUrl.value = defaultAxios.getBaseUrl() + "/api/tdengine/managerpoints/updateTagTnByFile";
  setTimeout(() => {
    init()
  }, 100)
})

onBeforeUnmount(() => {
  console.log("组件销毁")
})

watch((deep) => store.info, val => {
  if (val && store.connected) {
    init();
  }
})


const init = () => {
  height.value = document.documentElement.clientHeight - 30;
  dialogWidth.value = document.documentElement.clientWidth * 0.8 - 10;
}

const searchConidtionST = () => {
  if (currentDb.value == null || currentDb.value == '') {
    ElMessage({
      message: '请先选择数据库',
      type: 'error',
    });
    return;
  }
  /**
     * 获取table列表
     */
  let payload = {
    ...store.info,
    dbName: currentDb.value
  };
  let param = {
    dbConfig: payload,
    tableName: searchWord.value,
    pageSize: pageSize.value,
    currentPage: currentPage.value
  }
  loading.value = true;
  showTopics(param).then(r => {
    stData.value = r.data.records.map((item: any, index: number) => {
      return item;
    });
    total.value = r.data.total;
    loading.value = false;
  }).catch(err => {
    ElMessage({
      message: '查询数据失败',
      type: 'error',
    });
    loading.value = false;
  });

}

const handleClick = (tab: any) => {
  console.log(tab)
}





const handleSizeChange = (val: number) => {
  searchConidtionST();
}
const handleCurrentChange = (val: number) => {
  searchConidtionST();
}





</script>

<style scoped>
/* 添加一些样式以适应你的需求 */
.ml-3 {
  margin-left: 20px;
}

.demo-tabs {
  width: 100%;
  height: 100%;
}

.el-sub-menu.is-active {
  background-color: #a2d2ff;
}

/* 覆盖菜单激活项的背景颜色 */
.el-menu-item.is-active {
  color: hsl(246, 100%, 54%) !important;
  /* 选中项的文本颜色 */
}


.pcolor {
  background-color: #051422;
}

.right {
  padding-left: 20px;
  line-height: 30px;
  float: right;
}

.codemirror {
  width: 100%;
  height: 300px;
}

.monaco-editor {
  width: 100%;
  height: 100%;
}
</style>